package com.smalldoor.thread.sync;

//买票 有线程安全问题 加上synchronized方法保证线程安全
public class UnSafeForByTicket {

    public static void main(String[] args) {
        BuyTicket place = new BuyTicket();

        Thread t1 = new Thread(place, "张三");
        Thread t2 = new Thread(place, "李四");
        Thread t3 = new Thread(place, "黄牛党");

        t1.start();
        t2.start();
        t3.start();
    }
}

class BuyTicket implements Runnable {

    private int ticketsNums = 10;

    private boolean flag = true;

    private synchronized void buy() throws InterruptedException {
        if (ticketsNums <= 0) {
            flag = false;
            return;
        }

        //模拟延时
        Thread.sleep(100);
        System.out.println(Thread.currentThread().getName() + "买到了第" + ticketsNums-- + "张票");
    }


    @Override
    public void run() {
        while (flag) {
            try {
                buy();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
